<?php
declare(strict_types=1);

namespace seecms\controller;

use seecms\lib\builder\column\ImageColumn;
use seecms\lib\builder\control\ImageControl;
use seecms\See;
use seecms\lib\Auth;
use seecms\lib\Image;
use seecms\SeeException;
use seecms\SeeLang;
use seecms\lib\response\JsonResponse;

class Attachment extends Resource
{
    protected $table_name = 'see_attachment';

    protected $dictionary_name = 'attachment';

    protected function pageTitle(): string
    {
        return __('attachment.page_title');
    }

    protected function query(): array
    {
        return [
            'ext'
        ];
    }

    protected function columns(): array
    {
        return [
            'id.80',
            ImageColumn::init('thumb'),
            'filename.240',
            'ext',
            'size_text',
            'driver',
            'mime',
            'created_at',
        ];
    }

    protected function controls(): array
    {
        return [
            ImageControl::init('filepath')->setLabel(SeeLang::attachment('image'))->setDisk('attachment')->setLimit(20)->setChoose(),
        ];
    }

    /**
     * @return string
     */
    public function form(): string
    {
        return $this->view('attachment/form',
            [
                'water' => See::config()->upload->water()
            ]
        );
    }

    /**
     * @return JsonResponse
     */
    public function upload(): JsonResponse
    {
        $upload = See::provider()->upload;
        $record = See::table()->attachment->where('md5', $upload->md5())->find();
        if ($record && $record['filepath']) {
            return JsonResponse::error('请不要重复上传,图片索引【' . $record['id'] . '】');
        }

        // 移动文件
        $filepath = $upload->move();

        $config = See::config()->upload;
        $root = $config->root();
        $full_path = $root . $filepath;
        $filename = pathinfo($filepath, PATHINFO_BASENAME);
        // 缩略图路径
        $thumb_dir = $config->directoryThumb();
        $thumb_save_name = $thumb_dir . '/' . $filename;

        try {
            if (!is_dir($root . $thumb_dir) && !mkdir($root . $thumb_dir, 0777, true)) {
                return JsonResponse::error('创建缩略图保存目录失败');
            }

            $image = new Image($full_path);
            $image->thumb();
            $image->save($root . $thumb_save_name);
        } catch (SeeException $exception) {

        }

        // 创建水印
        $water = See::request()->post('water');

        if ($water) {
            try {
                // 水印路径
                $water_dir = $config->directoryWater();
                if (!is_dir($root . $water_dir) && !mkdir($root . $water_dir, 0777, true)) {
                    return JsonResponse::error('创建水印保存目录失败');
                }
                // 水印保存
                $water_save_name = $water_dir . '/' . $filename;

                // 创建图片水印
                $image_index = See::request()->post('image');
                // 文字水印
                $text = See::request()->post('text');

                if ($image_index != -1) {
                    $source = $config->waterImageList()[$image_index] ?? null;
                    if ($source) {
                        $image = new Image($full_path);
                        $image->water($config->waterImageRoot() . $source);
                        if ($image->save($root . $water_save_name)) {
                            $filepath = $water_save_name;
                        }
                    }
                } elseif ($text) {
                    $image = new Image($full_path);
                    $image->text($text);
                    if ($image->save($root . $water_save_name)) {
                        $filepath = $water_save_name;
                    }
                }
            } catch (SeeException $exception) {

            }
        }

        $data['user_id'] = Auth::user()->uuid();
        $data['filepath'] = $filepath;
        $data['filename'] = $upload->getOriginalName();
        $data['mime'] = $upload->getOriginalMime();
        $data['ext'] = $upload->getOriginalExtension();
        $data['size'] = $upload->getSize();
        $data['md5'] = $upload->md5();
        $data['sha1'] = $upload->sha1();
        $data['thumb'] = $thumb_save_name;
        $data['driver'] = 'local';

        See::table()->attachment->insert($data);

        return JsonResponse::success(['url' => $filepath], SeeLang::upload('success'));
    }
}